/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yami.shop.bean.enums.UploadType;
import com.yami.shop.bean.model.AttachFile;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.util.ImgUploadUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.AttachFileMapper;
import com.yami.shop.qiniuy.QiNiuYunUtils;
import com.yami.shop.service.AttachFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @author lanhai
 */
@Service
public class AttachFileServiceImpl extends ServiceImpl<AttachFileMapper, AttachFile> implements AttachFileService {

	@Autowired
	private AttachFileMapper attachFileMapper;
	@Autowired
	private UploadManager uploadManager;
	@Autowired
	private BucketManager bucketManager;
	@Autowired
	private Qiniu qiniu;
	@Autowired
	private Auth auth;
	@Autowired
	private ImgUploadUtil imgUploadUtil;
	public final static String NORM_MONTH_PATTERN = "yyyy/MM/";

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String uploadFile(MultipartFile file) throws IOException {
		String extName = FileUtil.extName(file.getOriginalFilename());
		String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;
		AttachFile attachFile = new AttachFile();
		attachFile.setFilePath(fileName);
		attachFile.setFileSize(file.getBytes().length);
		attachFile.setFileType(extName);
		attachFile.setUploadTime(new Date());
		if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
			// 本地文件上传
			attachFileMapper.insert(attachFile);
			return imgUploadUtil.upload(file, fileName);
		} else {
			// 七牛云文件上传
//			String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
//			Response response = uploadManager.put(file.getBytes(), fileName, upToken);
//			Json.parseObject(response.bodyString(),  DefaultPutRet.class);





//			//获取上传文件的原始文件名
//			String originalFilename = file.getOriginalFilename();
//			//获取文件的扩展名
//			int index = originalFilename.lastIndexOf(".");//pic1.jpg
//			//找到文件名中最后一个点的位置
//			//截取后缀名
//			String extention = originalFilename.substring(index);//.jpg
//
//			String fileNamex =  UUID.randomUUID().toString()+ extention;
			//上传至七牛云
			QiNiuYunUtils.upload2Qiniu2(file.getBytes(), fileName);
//			return "http://sn6dt32ir.hb-bkt.clouddn.com/"+fileNamex;
//			return "http://sn6dt32ir.hb-bkt.clouddn.com/"+fileName;
			return fileName;
		}
	}

	// @RequestMapping("/upload")
	//    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) throws IOException {
	//        System.err.println("---------------------------");
	//        System.err.println(imgFile.getOriginalFilename());
	//        //---------------------------
	//        //288d90e5-fdf1-4032-af79-642458ceddb1.jpg
	//        try {
	//            //获取上传文件的原始文件名
	//            String originalFilename = imgFile.getOriginalFilename();
	//            //获取文件的扩展名
	//            int index = originalFilename.lastIndexOf(".");//pic1.jpg
	//            //找到文件名中最后一个点的位置
	//            //截取后缀名
	//            String extention = originalFilename.substring(index);//.jpg
	//            String fileName =  UUID.randomUUID().toString()+ extention;
	//
	//            //上传至七牛云
	//            QiNiuYunUtils.upload2Qiniu2(imgFile.getBytes(), fileName);
	//            //当用户上传图片后，将图片名称保存到redis的一个Set集合中
	//            redisClient.sadd( ResultConstant.UPLOAD_IMG_LIST, fileName);
	//            return Result.OK(true,ResultConstant.UPLOAD_PHOTO_SUCCESS,fileName);
	//        } catch (IOException e) {
	//            e.printStackTrace();
	//            return Result.ERROR(false, ResultConstant.UPLOAD_PHOTO_ERROR);
	//        }
	//    }

	@Override
	public void deleteFile(String fileName){
		attachFileMapper.delete(new LambdaQueryWrapper<AttachFile>().eq(AttachFile::getFilePath,fileName));
		try {
			if (Objects.equals(imgUploadUtil.getUploadType(), UploadType.LOCAL.value())) {
				imgUploadUtil.delete(fileName);
			} else if (Objects.equals(imgUploadUtil.getUploadType(), UploadType.QINIU.value())) {
				bucketManager.delete(qiniu.getBucket(), fileName);
			}
		} catch (QiniuException e) {
			throw new RuntimeException(e);
		}
	}
}
